package com.fangfei.runtest.service;

import com.fangfei.runtest.Config.TestConfig;
import com.fangfei.runtest.Config.TestEnum;
import com.fangfei.runtest.handler.TestRejected;
import com.fangfei.runtest.worker.TestTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Order(1000)
public class TestCommandLineRunner implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RestTemplate restTemplate;

    private TestConfig testConfig;

    @Override
    public void run(String... args) throws Exception {

        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                TestEnum.CORESIZE.getValue(),           //coreSize
                TestEnum.MAXSIZE.getValue(),            //MaxSize
                TestEnum.ALIVETIME.getValue(),          //60
                TimeUnit.SECONDS,                       //时间类型
                new ArrayBlockingQueue<>(5),   //指定一种队列 （有界队列）//new LinkedBlockingQueue<Runnable>()
                new TestRejected()                      //new DiscardOldestPolicy()
        );

        for (int i=1;i<=TestEnum.CORESIZE.getValue();i++){
            testConfig = new TestConfig(jdbcTemplate,restTemplate);
            pool.execute(new TestTask(i,testConfig));
        }

        pool.shutdown();
    }
}
